package cn.seocoo.platform.user.service.impl;

import cn.seocoo.platform.car.dto.CarDto;
import cn.seocoo.platform.common.constant.ClassContants;
import cn.seocoo.platform.common.core.text.Convert;
import cn.seocoo.platform.common.pay.alipay.AliPayUtils;
import cn.seocoo.platform.common.utils.AmountUtils;
import cn.seocoo.platform.common.utils.CodeGeneratorUtils;
import cn.seocoo.platform.common.utils.StringUtils;
import cn.seocoo.platform.order.domain.AuthOrder;
import cn.seocoo.platform.order.mapper.AuthOrderMapper;
import cn.seocoo.platform.sysArea.domain.SysArea;
import cn.seocoo.platform.sysArea.mapper.SysAreaMapper;
import cn.seocoo.platform.user.domain.AppUser;
import cn.seocoo.platform.user.domain.AppUserDto;
import cn.seocoo.platform.user.dto.UnitFrom;
import cn.seocoo.platform.user.dto.UserFrom;
import cn.seocoo.platform.user.dto.UserInfo;
import cn.seocoo.platform.user.dto.UserTypeDto;
import cn.seocoo.platform.user.mapper.AppUserMapper;
import cn.seocoo.platform.user.service.IAppUserService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * APP注册用户 服务层实现
 *
 * @author wujian
 * @date 2019-12-20
 */
@Service
public class AppUserServiceImpl implements IAppUserService {

    @Autowired
    private AppUserMapper appUserMapper;

    @Autowired
    private AuthOrderMapper authOrderMapper;

    @Autowired
    private SysAreaMapper sysAreaMapper;

    /**
     * 查询APP注册用户信息
     *
     * @param id APP注册用户ID
     * @return APP注册用户信息
     */
    @Override
    public AppUser selectAppUserById(Integer id) {
        return appUserMapper.selectAppUserById(id);
    }

    /**
     * 查询APP注册用户列表
     *
     * @param appUser APP注册用户信息
     * @return APP注册用户集合
     */
    @Override
    public List<AppUser> selectAppUserList(AppUser appUser) {
        return appUserMapper.selectAppUserList(appUser);
    }

    /**
     * 新增APP注册用户
     *
     * @param appUser APP注册用户信息
     * @return 结果
     */
    @Override
    public int insertAppUser(AppUser appUser) {
        return appUserMapper.insertAppUser(appUser);
    }

    /**
     * 修改APP注册用户
     *
     * @param appUser APP注册用户信息
     * @return 结果
     */
    @Override
    public int updateAppUser(AppUser appUser) {
        return appUserMapper.updateAppUser(appUser);
    }

    /**
     * 删除APP注册用户对象
     *
     * @param ids 需要删除的数据ID
     * @return 结果
     */
    @Override
    public int deleteAppUserByIds(String ids) {
        return appUserMapper.deleteAppUserByIds(Convert.toStrArray(ids));
    }

    @Override
    public AppUser selectAppUserByLoginName(String loginName) {
        return appUserMapper.selectAppUserByLoginName(loginName);
    }


    @Override
    public AppUser selectAppUserByOpenId(AppUser appUserTemp) {
        return appUserMapper.selectAppUserByOpenId(appUserTemp);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> loginUser(AppUser appUserTemp) {
        //登录成功状态:loginType(0:失败;1:成功);otherType 登录方式(0:验证码登录;1:第三方)
        Map<String, Object> map = new HashMap<>();
        map.put("loginType", "0");
        map.put("otherType", "0");
        AppUserDto appUserDto = null;
        //根据登录账号判断登录方式,并校验当用户用第三方登录的时候,判断用户有没有绑定手机号
        //第三方登录
        if (StringUtils.isNotEmpty(appUserTemp.getWechatOpenId()) || StringUtils.isNotEmpty(appUserTemp.getQqOpenId())) {
            map.put("otherType", "1");
            appUserDto = appUserMapper.selectAppUserDtoByOpenId(appUserTemp);
            //如果只有第三方账号，即返回map让用户绑定手机号
            if (appUserDto == null && StringUtils.isEmpty(appUserTemp.getLoginName())) {
                return map;
            }
            //如果没有第三方信息，则直接手机号登录
        } else if (StringUtils.isNotEmpty(appUserTemp.getLoginName())) {
            appUserDto = appUserMapper.selectAppUserDtoByLoginName(appUserTemp.getLoginName());
        }

        //未注册或未绑定
        if (appUserDto == null) {
            appUserDto = firstRegistUser(appUserTemp.getLoginName(), appUserTemp.getWechatOpenId(), appUserTemp.getQqOpenId());
        }
        //登录成功
        if (appUserDto != null) {
            map.put("loginType", "1");
            map.put("appUserDto", appUserDto);
        }
        return map;

    }

    /**
     * @return void
     * @Author WuJian
     * @Description //用户认证
     * @Date 18:56 2019/12/29
     * @Param [userFrom]
     **/
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> save(UserFrom userFrom) throws Exception {
        Map<String, Object> map = new HashMap<>();
        AppUser appUser = appUserMapper.selectAppUserById(userFrom.getAppUserId());
        //用户存在并且用户状态为匿名用户
        if (appUser != null && AppUser.ANANYMOUS_USER.equals(appUser.getUserType())) {

            BeanUtils.copyProperties(userFrom, appUser);
            appUser.setIsPayFlag(AppUser.NO_PAY_FLAG);
            appUser.setUserAuthFlag(AppUser.NO_USER_AUTHER);
            appUserMapper.updateAppUser(appUser);
            //<---------------------创建一个认证订单------------------->
            AuthOrder order = new AuthOrder();
            order.setAppUserId(appUser.getId());
            String amountStr = userFrom.getAutherAmount();
            Integer amount = Integer.valueOf(AmountUtils.changeY2F(amountStr));
            String orderNumber = CodeGeneratorUtils.nextId();
            order.setOrderNumber(orderNumber);
            order.setPayAmount(amount);
            order.setAmount(amount);
            //支付方式
            String payType = userFrom.getPayType();
            order.setPayType(payType);
            order.setOrderStatus(ClassContants.WAIT_ORDER_STATUS);
            order.setDelFlag(ClassContants.NO_DEL_FLAG);
            order.setCreateTime(new Date());
            authOrderMapper.insertAuthOrder(order);
            //<!---------------自定义map开始:-------------->
            Map<String, Object> orderMsg = new HashMap<>();
            orderMsg.put("key", "auther");
            orderMsg.put("orderNumber", orderNumber);
            //<!---------------自定义map结束:-------------->

            //如果是支付宝支付,调用支付宝
            if (ClassContants.ALI_PAY_TYPE.equals(payType)) {
                map.put("name", payType);
                String ordermsg = AliPayUtils.aliPay(orderMsg, orderNumber, userFrom.getAutherAmount());
                map.put("value", ordermsg);
                //如果是微信支付,调用微信
            } else if (ClassContants.WECHAT_PAY_TYPE.equals(payType)) {
                map.put("name", payType);
            }


        }
        return map;


    }

    /**
     * @return void
     * @Author WuJian
     * @Description //商家认证
     * @Date 13:55 2019/12/30
     * @Param [unitFrom]
     **/
    @Override
    public Integer autherUnit(UnitFrom unitFrom) {
        AppUser appUser = appUserMapper.selectAppUserById(unitFrom.getAppUserId());
        if (appUser != null && AppUser.AUTHER_USER.equals(appUser.getUserType())) {
            BeanUtils.copyProperties(unitFrom, appUser);
            appUser.setUnitAuthFlag(AppUser.IS_UNIT_AUTHER);
            appUser.setUnitCreateTime(new Date());
            int row = appUserMapper.updateAppUser(appUser);
            return row;
        }
        return 0;
    }

    /**
     * @return cn.seocoo.platform.user.dto.UserInfo
     * @Author WuJian
     * @Description //获取用户信息
     * @Date 19:00 2019/12/30
     * @Param [appUserId]
     **/
    @Override
    public UserInfo getApiUserInfo(Integer appUserId) {
        AppUser appUser = appUserMapper.selectAppUserById(appUserId);
        UserInfo userInfo = new UserInfo();
        if (appUser != null) {
            userInfo.setHeadImageUrl(appUser.getHeadImageUrl());
            userInfo.setNickName(appUser.getNickName());
            userInfo.setPhoneNumber(appUser.getPhoneNumber());
            userInfo.setUserType(appUser.getUserType());
            if (AppUser.BUSINESSES_USER.equals(appUser.getUserType())) {
                //计算车辆数 和 入驻时长
                userInfo.setSellCount(9);
                userInfo.setYear("2");
                userInfo.setUnitContent(appUser.getUnitContent());
                userInfo.setRealName(appUser.getRealName());
                userInfo.setBusinessLicense(appUser.getBusinessLicense());
                SysArea area = sysAreaMapper.selectAreaByCode(appUser.getAreaCode());
                if (area != null) {
                    String margerName = area.getMergerName().replace(",", "");
                    userInfo.setAddress(margerName + appUser.getUnitAddress());
                }

            }
        }

        return userInfo;
    }

    /**
     * @return java.util.List<cn.seocoo.platform.car.dto.CarDto>
     * @Author WuJian
     * @Description //我的发布
     * @Date 14:05 2020/1/3
     * @Param [pageNum, pageSize, appUserId]
     **/
    @Override
    public List<CarDto> getCarList(Integer pageNum, Integer pageSize, Integer appUserId) {
        PageHelper.startPage(pageNum == null ? 1 : pageNum, pageSize == null ? 10 : pageSize);
        return appUserMapper.getCarList(appUserId);
    }

    /**
     * @Author WuJian
     * @Description //卖车时,校验用户发布的车辆
     * @Date 15:58 2019/12/30
     * @Param [appUserId]
     * @return cn.seocoo.platform.api.util.JSONResult
     **/
    @Override
    public Map<String, String> checkUserCarNum(Integer appUserId) {
        Map<String, String> map = new HashMap();
        AppUser appUser = appUserMapper.selectAppUserById(appUserId);
        //查询当前用户发布了几辆车
        Integer count = appUserMapper.getCountForUserCar(appUserId);
        if(AppUser.BUSINESSES_USER.equals(appUser.getUserType())){
            map.put("name","4");
            map.put("value","已是商家,可以发布多辆车");
            return map;
            //如果是匿名
        }else if(AppUser.ANANYMOUS_USER.equals(appUser.getUserType())){
            if(count == 0){
                //已缴费
                map.put("name","0");
                map.put("value","匿名用户,未发布车辆");
                return map;
            }else{
                map.put("name","1");
                map.put("value","匿名用户,已发布过车辆");
                return map;
            }
        }else if(AppUser.AUTHER_USER.equals(appUser.getUserType())){
            if(count == 0){
                //已缴费
                map.put("name","2");
                map.put("value","认证用户,未发布车辆");
                return map;
            }else{
                map.put("name","3");
                map.put("value","认证用户,已发布车辆车辆");
                return map;
            }
        }
      return map;
    }

    @Override
    public AppUserDto firstRegistUser(String loginName, String wechatOpenId, String qqOpenId) {
        AppUser appUser = new AppUser();
        appUser.setLoginName(loginName);
        appUser.setPhoneNumber(loginName);
        appUser.setWechatOpenId(wechatOpenId);
        appUser.setQqOpenId(qqOpenId);
        //手机号已经注册过，绑定openId
        AppUser user = selectAppUserByLoginName(loginName);
        if (user != null) {
            appUser.setId(user.getId());
            appUserMapper.updateAppUser(appUser);
        } else {
            appUser.setDelFlag(ClassContants.NO_DEL_FLAG);
            appUser.setForbidden(ClassContants.NO_FORBIDDEN);
            appUser.setNickName(ClassContants.TEMPORARY_NAME + "_" + (int) (Math.random() * 100000 + 100000) + "");
            //匿名用户
            appUser.setUserType(AppUser.ANANYMOUS_USER);
            appUserMapper.insertAppUser(appUser);
        }
        return appUserMapper.selectAppUserDtoByLoginName(loginName);
    }

}
